<?php

namespace app\api\model;

use think\Db;

class UserProfile extends Common
{
    static public function initd($user_id, $data = [])
    {
        $UserProfile = self::get(['user_id' => $user_id]);

        if (!$UserProfile) {
            $where['user_id']=$user_id;
            $where['create_time'] = time();
            // $where['name'] = '相亲用户'.rand(1000,9999);
            self::create($where);
        }
        self::sync($user_id);
    }
    static public function change($user_id, $data = [])
    {
        $UserProfile = self::get(['user_id' => $user_id]);

        $tableFields = Db::getTableInfo('user_profile', 'fields');
        $unsetKey = ['id', 'create_time', 'update_time'];

        $where = ['user_id' => $user_id];

        foreach ($data as $key => $value) {
            if (in_array($key, $unsetKey)) continue;
            if (!in_array($key, $tableFields)) continue;
            $where[$key] = $value?:'';
        }
        if ($UserProfile) {
            $where['id'] = $UserProfile['id'];
            $where['update_time'] = time();
            $method = 'update';
        } else {
            $where['create_time'] = time();
            $method = 'create';
        }
        self::$method($where);
    }
    static public function sync($user_id, $data = [])
    {
        $UserProfile = self::get(['user_id' => $user_id]);

        $tableFields = Db::getTableInfo('user_profile', 'fields');
        $setKey = ['is_car_purchase', 'is_house_purchase', 'education_background', 'monthly_salary', 'emotion', 'sex', 'age'];

        $user = Db::name('user')->find($user_id);
        $where = ['user_id' => $user_id];

        $data = array_merge($data, $user);
        foreach ($data as $key => $value) {
            if (!in_array($key, $setKey)) continue;
            if (!in_array($key, $tableFields)) continue;
            $where[$key] = $value?:'';
        }
        if ($UserProfile) {
            $where['id'] = $UserProfile['id'];
            $where['update_time'] = time();
            $method = 'update';
        }
        self::$method($where);
    }
}
